package com.rc.saas.tenant.controller.elec;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.utils.QrCodeUtils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.elec.*;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenfor;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.operator.RcOperatorExample;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantManufacturer;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.search.elec.ElecGunSearch;
import com.rc.saas.tenant.search.elec.ElecPileFailureSearch;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.elec.*;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenforService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.tenant.TenantManufacturerService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.search.elec.ElecPileSearch;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.elec.ElecPileResultVo;
import com.rc.saas.tenant.vo.elec.ElecStationAndCityName;
import com.rc.saas.tenant.vo.elec.UnlockReq;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date zz/10/23
 */
@Controller
@RequestMapping("/elecPile")
public class ElecPileController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ElecPileController.class);


    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private TenantManufacturerService tenantManufacturerService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private HlhtTenantOpenforService hlhtTenantOpenforService;

    @Autowired
    private ElecPileHostService elecPileHostService;

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private PlatformAreaService areaService;

    @Autowired
    private RcOperatorService rcOperatorService;

    @Autowired
    private TenantRoleService tenantRoleService;
    //@Value("${hardware.server}")
    //private String serverUrl;

    /**
     * 跳转桩页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String elecPilePage() {
        return "/templates/elec/elecPile";
    }


    /**
     * 特供监控地图
     *
     * @return
     */
    @RequestMapping(value = "/map/{elecStationId}", method = RequestMethod.GET)
    public String elecMpa(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecPile";
    }

    /**
     * 返回桩列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPagePile", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPagePile(ElecPileSearch elecPileSearchVo) {
        TenantUser user = ShiroUtils.getSessionUser();
        elecPileSearchVo.setLoginName(user.getLoginName());
        PageInfo<ElecPileResultVo> pageInfo = elecPileService.listPagePile(elecPileSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出充电桩列表
     */
    @ResponseBody
    @RequestMapping(value = "/exportPile", method = RequestMethod.GET)
    public TResponse exportPile(ElecPileSearch elecPileSearchVo, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(elecPileSearchVo);
            PageInfo<ElecPileResultVo> pageInfo = elecPileService.listPagePile(elecPileSearchVo);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("充电桩列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecPileResultVo.class).sheet("充电桩列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出充电桩列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 跳转编辑桩页面
     *
     * @return
     */
    @RequestMapping(value = "/editElecPile/{elecPileId}", method = RequestMethod.GET)
    public String editElecPile(@PathVariable("elecPileId") Long elecPileId, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecPileId);
        model.addAttribute("elecPile", elecPile);
        List<ElecStation> stations = elecStationService.listStationBySelf(user.getTenantCode());
        model.addAttribute("stations", stations);
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        List<RcOperator> operators = operatorService.loadOperator(user.getLoginName());
        model.addAttribute("operators", operators);
        return "/templates/elec/editElecPile";
    }

    /**
     * 跳转桩详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detailElecPile/{elecPileId}", method = RequestMethod.GET)
    public String detailPile(@PathVariable("elecPileId") Long elecPileId, Model model) {
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecPileId);
        TenantManufacturer manufacturer = tenantManufacturerService.selectByPrimaryKey(elecPile.getManufacturerId());
        if (elecPile.getElecStationId()!=null){
            ElecStationAndCityName elecStation = elecStationService.selectStationAndCity(elecPile.getElecStationId());
            Date operateStartTime = elecStation.getOperateStartTime();
            if (operateStartTime != null) {
                elecStation.setOperateStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateStartTime));
            }
            model.addAttribute("elecStation", elecStation);
            List<PlatformProvince> provinces = areaService.listAllProvince();
            model.addAttribute("provinces", provinces);
            //model.addAttribute("elecGun", elecGun);
        }
        if (elecPile.getOperatorId()!=null){
            RcOperator operator = operatorService.selectByPrimaryKey(elecPile.getOperatorId());
            model.addAttribute("operator", operator);
        }
        model.addAttribute("elecPile", elecPile);
        model.addAttribute("manufacturer", manufacturer);
        return "/templates/elec/detailElecPile";
    }

    /**
     * 跳转增加桩页面
     *
     * @return
     */
    @RequestMapping(value = "/addElecPile", method = RequestMethod.GET)
    public String addElecPile(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<ElecStation> stationList = elecStationService.listStationBySelf(user.getTenantCode());
        List<TenantManufacturer> tenantManufacturerList = tenantManufacturerService.selectByTenantCode(user.getTenantCode(), "1");
        model.addAttribute("tenantManufacturerList", tenantManufacturerList);
        model.addAttribute("stationList", stationList);
        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantCode());
        model.addAttribute("tenant", tenant);
        List<RcOperator> operators = operatorService.loadOperator(user.getLoginName());
        model.addAttribute("operators", operators);
        return "/templates/elec/addElecPile";
    }

    /**
     * 保存编辑桩
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecPile", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecPile(ElecPile elecPile) {
        TenantUser user = ShiroUtils.getSessionUser();
        //  if (!BeanUtil.isValid(elecStationPrice.getPriceCode(), elecStationPrice.getElecPrice(),
        //          elecStationPrice.getServicePrice(),
        //          elecStationPrice.getBeginTime(), elecStationPrice.getEndTime())) {
        //      return TResponse.FAIL("请输入正确的参数");
        //  }

        try {

            TResponse tResponse = elecPileService.saveOrUpdateElecPile(elecPile, user.getTenantCode(), user.getLoginName());
            return tResponse;
        } catch (Exception e) {
            logger.error("保存桩失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 删除桩和对应的枪
     *
     * @return
     */
    @RequestMapping(value = "/deleteElecPile", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteElecPile(Long elecPileId) {
        try {
            elecPileService.deletePileAndGun(elecPileId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除桩失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 桩的上线或者下线
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public TResponse updateStatus(Long elecPileId) {
        try {
            elecPileService.changeStatus(elecPileId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更新状态失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 跳转枪页面
     *
     * @return
     */
    @RequestMapping(value = "/elecGun/{elecPileId}", method = RequestMethod.GET)
    public String elecGunPage(@PathVariable("elecPileId") Long elecPileId, Model model) {
        model.addAttribute("elecPileId", elecPileId);
        return "/templates/elec/elecGun";
    }

    /**
     * 返回枪列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listElecGun", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listElecGun(ElecGunSearch elecGunSearch) {
        PageInfo<ElecGun> pageInfo = elecGunService.listPageByCondition(elecGunSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 加载加盟商信息
     *
     * @return
     */
    @RequestMapping(value = "/loadOperator", method = RequestMethod.GET)
    @ResponseBody
    public RcOperator loadOperator(Long elecStationId) {
       ElecStation es =  elecStationService.selectByPrimaryKey(elecStationId);
        RcOperator operator = null;
       if (es!=null){
           operator = operatorService.selectByPrimaryKey(es.getOperatorId());
       }

       if (operator!=null){
           System.out.println(operator.getOperatorName());

           return operator;
       }
        return  new RcOperator();
    }


    /**
     * 跳转编辑枪页面
     *
     * @return
     */
    @RequestMapping(value = "/editElecGun/{elecGunId}", method = RequestMethod.GET)
    public String editElecGun(@PathVariable("elecGunId") Long elecGunId, Model model) {
        ElecGun elecGun = elecGunService.selectByPrimaryKey(elecGunId);
        List<TenantManufacturer> tenantManufacturer = tenantManufacturerService.selectByTenantCode(elecGun.getTenantCode(), "2");
        model.addAttribute("tenantManufacturer", tenantManufacturer);
        model.addAttribute("elecGun", elecGun);
        return "/templates/elec/editElecGun";
    }


    /**
     * 跳转枪详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detailElecGun/{elecGunId}", method = RequestMethod.GET)
    public String detailElecGun(@PathVariable("elecGunId") Long elecGunId, Model model) {
        ElecGun elecGun = elecGunService.selectByPrimaryKey(elecGunId);
        model.addAttribute("elecGun", elecGun);
        if (elecGun.getElecStationId()!=null){
            ElecStation elecStation = elecStationService.selectByPrimaryKey(elecGun.getElecStationId());
            model.addAttribute("elecStation", elecGun);
            //model.addAttribute("elecGun", elecGun);
        }
        if (elecGun.getOperatorId()!=null){
            RcOperator operator = operatorService.selectByPrimaryKey(elecGun.getOperatorId());
            model.addAttribute("operator", operator);
        }

        return "/templates/elec/detailElecGun";
    }

    /**
     * 跳转增加枪页面
     *
     * @return
     */
    @RequestMapping(value = "/addElecGun/{elecPileId}", method = RequestMethod.GET)
    public String addElecGun(@PathVariable("elecPileId") Long elecPileId, Model model) {
        model.addAttribute("elecPileId", elecPileId);
        return "/templates/elec/addElecGun";
    }


    /**
     * 保存编辑枪
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecGun", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecGun(ElecGun elecGun) {
        TenantUser user = ShiroUtils.getSessionUser();
        //  if (!BeanUtil.isValid(elecStationPrice.getPriceCode(), elecStationPrice.getElecPrice(),
        //          elecStationPrice.getServicePrice(),
        //          elecStationPrice.getBeginTime(), elecStationPrice.getEndTime())) {
        //      return TResponse.FAIL("请输入正确的参数");
        //  }
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());

        try {
            Date date = new Date();
            elecGun.setTenantCode(user.getTenantCode());
            elecGun.setLastUpdatedBy(user.getLoginName());
            elecGun.setLastUpdatedTime(date);

            if (elecGun.getElecGunId() == null) {
                elecGun.setElecStationId(elecPile.getElecStationId());
                elecGun.setCreatedBy(user.getLoginName());
                elecGun.setCreatedTime(date);
                elecGunService.insertSelective(elecGun);
            } else {
                elecGunService.updateByPrimaryKeySelective(elecGun);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存枪失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除对应的枪
     *
     * @return
     */
    @RequestMapping(value = "/deleteElecGun", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteElecGun(Long elecGunId) {
        try {
            elecGunService.deleteByPrimaryKey(elecGunId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除桩失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 更改枪的状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateGunStatus", method = RequestMethod.POST)
    public TResponse updateGunStatus(Long elecGunId) {
        try {
            elecGunService.updateGunStatus(elecGunId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 解锁功能
     *
     * @param elecGunId
     * @return
     */
    @RequestMapping(value = "sendUnlock", method = RequestMethod.POST)
    @ResponseBody
    public TResponse sendUnlock(Long elecGunId) {
        try {
            ElecGun elecGun = elecGunService.selectByPrimaryKey(elecGunId);
//            ElecStation elecStation = elecStationService.selectByPrimaryKey(elecGun.getElecStationId());
//            ElecPileHost elecPileHost=elecPileHostService.selectByPrimaryKey(elecGun.getElecPileId());


            UnlockReq unlockReq = new UnlockReq();
            unlockReq.setPileId(elecGun.getElecPileId());
            unlockReq.setGunNum(elecGun.getGunNum());

           /* TResponse tResponse = chargerClientRouter.sendUnlock(unlockReq);
            if (tResponse.getStatus() == HttpConstant.STATUS_SUCCESS) {
                return tResponse;
            } else {
                return TResponse.FAIL("调用解锁接口失败");
            }*/
            return  null;
        } catch (Exception e) {
            logger.error("发送解锁指令失败", e);
            return TResponse.FAIL("发送解锁指令失败");
        }
    }


    /**
     *
     *
     * 中电联标准二维码生成
     *
     * @param gunNo
     * @return
     */
    @RequestMapping(value = "/genElecGunQrCode/{gunNo}", method = RequestMethod.GET)
    public String genElecGunQrCode(@PathVariable("gunNo") String gunNo, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user == null) {
            return null;
        }
        String url = QrCodeUtils.createCecQRCode(user.getTenantCode(), gunNo);
        model.addAttribute("qrcode", url);

        //小程序二维码生成
        String miniQrcode = QrCodeUtils.createMiniQRCode(user.getTenantCode(), gunNo);
        model.addAttribute("miniQrcode", miniQrcode);

        //新增第三方二维码
        HlhtTenantOpenfor hlhtTenantOpenfor = hlhtTenantOpenforService.selectTenantOpenforByGunNo(user.getTenantCode(), gunNo);
        if (hlhtTenantOpenfor != null) {
            String hlhtQrcode = QrCodeUtils.createCecQRCode(hlhtTenantOpenfor.getHlhtTenantCode(), gunNo);
            model.addAttribute("hlhtQrcode", hlhtQrcode);
        }


        //微信公众号网页授权
        //ElecGun elecGun = elecGunService.selectGunByGunNo(gunNo);
        //String wechatQrcode = QrCodeUtils.createWechatQRCode(user.getTenantCode(), gunNo, elecGun.getElecStationId().toString());
        //model.addAttribute("qrcodeWechat", wechatQrcode);

        return "/templates/elec/elecGunQrcode";
    }


    /**
     * 生成二维码地址
     *
     * @param gunNo
     * @return
     */
    @RequestMapping(value = "/genElecGunQrCodeUrl", method = RequestMethod.GET)
    public TResponse genElecGunQrCodeUrl(String gunNo) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user == null) {
            return null;
        }
        String url = QrCodeUtils.createCecQRCode(user.getTenantCode(), gunNo);
        return TResponse.SUCCESS_DATA(url);
    }

    /**
     * 跳转电桩实时故障页面
     *
     * @return
     */
    @RequestMapping(value = "/pileFailure", method = RequestMethod.GET)
    public String pileFailurePage() {
        return "/templates/elec/pileFailure";
    }

    /**
     * 返回电桩实时故障列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPileFailure", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPileFailure(ElecPileFailureSearch elecPileFailureSearch) {
        PageInfo<ElecPile> pageInfo = elecPileService.searchPileFailure(elecPileFailureSearch);
        // WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return null;
    }


}
